<script src="../../i18n/zh.js"></script>
<template>
  <div class="home-index">
    <!--    过题榜单-->
    <div class="rank">
      <!--      题目通过数量-->
      <el-card class="box-card">
        <div slot="header" class="clearfix">
          <el-dropdown @command="handleProblemCommand">
            <span class="el-dropdown-link">
<!--              练习过题量榜单-->
              {{ $t('homeMode.acceptProblemLeft')}}
            </span>
            <el-dropdown-menu slot="dropdown">
              <el-dropdown-item command="week">{{ $t('homeMode.lastWeek') }}</el-dropdown-item>
              <el-dropdown-item command="month">{{  $t('homeMode.lastMonth') }}</el-dropdown-item>
              <el-dropdown-item command="year">{{  $t('homeMode.lastYear') }}</el-dropdown-item>
              <el-dropdown-item command="all">{{  $t('homeMode.lastAll') }}</el-dropdown-item>
            </el-dropdown-menu>
          </el-dropdown>
        </div>
        <el-table :data="problemRank" style="width: 100%" class="text item">
          <el-table-column  width="50" label="#">
            <template slot-scope="scope">
              <!--              {{getValue(scope)}}-->
              <span :style="(scope.$index<3?'color: #f0d29a;':'')">{{scope.$index+1}}</span>
            </template>
          </el-table-column>
          <el-table-column  :label="$t('user')" >
            <template slot-scope="scope">

              <a href="javascript:void(0)" @click="$router.push('/main/user/detail/'+scope.row.userId)" :style="(scope.$index<5?'color:#ff0000;':'color:#2d8cf0;')"
                 v-html="getUserName(scope.row.userId)">
                 </a>
            </template>
          </el-table-column>
          <el-table-column prop="address"  fixed="right" :label="$t('count')" width="63">
            <template slot-scope="scope">
              <span :style="(scope.$index<5?'color:red;':'color:gray;')"> {{scope.row.acceptSum}} </span>
            </template>
          </el-table-column>
        </el-table>

      </el-card>
      <!--      比赛题目通过数量-->
      <el-card class="box-card">
        <div slot="header" class="clearfix">
          <el-dropdown @command="handleContestCommand">
            <span class="el-dropdown-link">
<!--              竞赛过题量榜单-->
              {{$t('homeMode.acceptProblemRight')}}
            </span>
            <el-dropdown-menu slot="dropdown">
              <el-dropdown-item command="week">{{$t('homeMode.lastWeek')}}</el-dropdown-item>
              <el-dropdown-item command="month">{{$t('homeMode.lastMonth')}}</el-dropdown-item>
              <el-dropdown-item command="year">{{$t('homeMode.lastYear')}}</el-dropdown-item>
              <el-dropdown-item command="all">{{$t('homeMode.lastAll')}}</el-dropdown-item>
            </el-dropdown-menu>
          </el-dropdown>
        </div>
        <el-table :data="contestRank" style="width: 100%" class="text item">
          <el-table-column  width="50" label="#">
            <template slot-scope="scope">
              <!--              {{getValue(scope)}}-->
              <span :style="(scope.$index<3?'color: #f0d29a;':'')">{{scope.$index+1}}</span>
            </template>
          </el-table-column>
          <el-table-column  :label="$t('user')" >
            <template slot-scope="scope">

              <a href="javascript:void(0)" @click="$router.push('/main/user/detail/'+scope.row.userId)" :style=" (scope.$index<5?'color:#ff0000;':'color:#2d8cf0;')">
                <div v-html="getUserName(scope.row.userId)"></div></a>
            </template>
          </el-table-column>
          <el-table-column prop="address"  fixed="right" :label="$t('count')" width="63">
            <template slot-scope="scope">
              <span :style="(scope.$index<5?'color:red;':'color:gray;')"> {{scope.row.acceptSum}} </span>
            </template>
          </el-table-column>
        </el-table>

      </el-card>
    </div>
<!--    日历-->
    <div class="today">
      <el-calendar v-model="today" height="150px">
        <template
            slot="dateCell"
            slot-scope="{date, data}">

          <p :class="data.isSelected ? 'is-selected' : ''"  @click="selectContest(date)">
            {{ data.day.split('-').slice(2).join('-') }}<br/>
            <el-popover v-if="getContestByTime(date)"
                placement="right" width="250" trigger="hover" >
              <router-link v-for="item in getContestByTime(date)" :key="item.id" style="font-size: 90%;margin: 10px;padding-top: 8px;"
                           :to="'/main/contest/detail/'+item.id">{{getHourMin(item.startTime)}} &nbsp;&nbsp;&nbsp;{{item.title}}<br/></router-link>
              <span slot="reference"  style="font-size: 68%;color: #c177e8">
                <i class="fa fa-eye fa-2x"></i>
              </span>
            </el-popover>

          </p>

        </template>
      </el-calendar>
    </div>

<!--    公告-->
    <div class="announcement" v-loading="announcementLoading">

      <div style="text-align: left">

        <el-button icon="el-icon-refresh" style="text-align: left;float: right;margin-right: 10px;" type="success" size="mini" @click="announcementLoading = true;getAnnouncementData()">
<!--          刷新-->
          {{$t('homeMode.flush')}}
        </el-button>
        <el-button v-if="isAdmin()" style="text-align: left;float: right;margin-right: 10px;" type="warning" size="mini" @click="$router.push('/main/home/announcement')">
<!--          管理-->
          {{$t('homeMode.management')}}
        </el-button>
        <h4 style="margin: 10px;">
<!--          公告-->
          {{$t('homeMode.accounce')}}
        </h4>
      </div>
      <hr style="border-color: #eeeeee"/>
      <div class="announcemet-body" v-for="item in announcementList" :key="item.id">

        <div style="margin: 10px;" v-html="item.text"></div>
        <div style="font-size: 80%;">
          <span><i class="el-icon-edit"></i>: {{item.createTime}}</span>
          &nbsp;&nbsp;&nbsp;
          <span><i class="fa fa-user-o "></i>: <span v-html="getUserName(item.userId)"></span></span>
        </div>
      </div>
      <el-pagination
          small
          :page-size="announcementParams.size"
          layout="prev, pager, next"
          :total="announcementTotal" @current-change="chg">
      </el-pagination>
    </div>
  </div>
</template>

<script lang="ts">
import * as contestApi from '@/api/contest'
import * as problemApi from '@/api/problem'
import * as userApi from '@/api/admin'
import {isLogin,isAdmin} from '@/utils/auth'
import * as announcementApi from '@/api/announcement.js'
export default {
  name: 'homeIndex',
  data() {
    return {
      today:new Date(),
      contestList:[],
      userNames:{}, //用户名称列表
      params:{
        page:1,
        size:100,
        rangeField:'start_time',
        between:this.getBetween(new Date()),
        to:this.getTo(new Date()),
      },
      problemRank:[], //题目榜单
      problemParams:{
        page:1,
        size:10,
        beginTime:'',
      },
      contestRank:[], //竞赛榜单
      contestParams:{
        page:1,
        size:10,
        beginTime:'',
      },

      rating:[],      //积分榜单
      //公告
      announcementList:[],
      announcementTotal:0,
      announcementParams:{
        page:1,
        size:1,
        status:0,
      },
      announcementLoading:false,
    };
  },
  methods: {

    isAdmin(){
      return isAdmin();
    },
    //当页数发生变化时执行
    chg(curpage) {
      //更新查询的页数
      this.announcementParams.page = curpage;
      //重新查询
      this.getAnnouncementData();
    },
    // 查看是否存在比赛，并返回
    getContestByTime(date){
      var res = []
      for(var i = 0;i<this.contestList.length;i++){
        var time = new Date(this.contestList[i].startTime);
        // console.info(date);
        // console.info(time);
        if(date.getMonth()==time.getMonth()&&date.getDate()==time.getDate())res.push(this.contestList[i]);
      }
      return res.length==0?null:res;
    },
    //本月第一天
    getBetween(date){
      var to = new Date(date);
      var year = to.getFullYear();
      var mon = to.getMonth();
      to = new Date(year,mon,1)
      return this.getFomatterDate(to);
    },
    //获取小时和分钟 HH:mm
    getHourMin(date){
      var time = new Date(date);
      var h = time.getHours();
      if(h<10)h = '0'+h;
      var m = time.getMinutes();
      if(m<10)m = '0'+m;
      return h+":"+m;
    },
    //格式化输出日期 yyyy-MM-dd
    getFomatterDate(to){
      var year = to.getFullYear();
      var mon = to.getMonth()+1;
      var day = to.getDate();
      // console.info(to)

      return year+'-'+mon+'-'+day;
    },
    //返回本月最后一天
    getTo(date){
      var to = new Date(date);
      var year = to.getFullYear();
      var mon = to.getMonth();
      return this.getFomatterDate(new Date(year,mon+1,0));
    },
    // 获取比赛列表
    getContestTable(){
      contestApi.getListData(this.params).then(res=>{
        if(res.data.data){

          this.contestList = res.data.data.dataList;
        }
      })
    },
    //获取过题榜单
    getProblemRankTable(){
      problemApi.getProblemRank(this.problemParams).then(async res=>{
        if(res.data.success){
          var tables = res.data.data.dataList;
          for(var i = 0;i<tables.length;i++){
            // console.info(tables[i].userId)
            if(!this.userNames[tables[i].userId]){
              await userApi.getEasyUserById({"id":tables[i].userId}).then(res2=>{
                if(res2.data.data&&res2.data.data.username){
                  // console.info("success="+res2.data.data.id);
                  this.userNames[res2.data.data.id] =   res2.data.data.username;
                }else{
                  this.userNames[tables[i].userId] =  '<span style="color:grey">'+this.$t("UnKnownUser")+'</span>';
                }
              });
            }
          }
          this.problemRank = tables;
        }
      })
    },
    //比赛最多过题量
    getContestRankTable(){
      contestApi.getContestRank(this.contestParams).then(async res=>{
        if(res.data.success){
          var tables = res.data.data.dataList;
          //获取用户名字
          for(var i = 0;i<tables.length;i++){
            // console.info(tables[i].userId)
            if(!this.userNames[tables[i].userId]){
              await userApi.getEasyUserById({"id":tables[i].userId}).then(res2=>{
                if(res2.data.data&&res2.data.data.username){
                  // console.info("success="+res2.data.data.id);
                  this.userNames[res2.data.data.id] =   res2.data.data.username;
                }else{
                  this.userNames[tables[i].userId] =  '<span style="color:grey">'+this.$t("UnKnownUser")+'</span>';
                }
              });
            }
          }
          this.contestRank = tables;

        }
      })
    },
    //根据信息userId获取用户名
    getUserName(id){
      return this.userNames[id];
    },
    //选择时间范围
    handleProblemCommand(command){
      this.problemParams.beginTime = this.getNextDay(command);
      this.getProblemRankTable();
    },
    //选择时间范围
    handleContestCommand(command){
      this.contestParams.beginTime = this.getNextDay(command);
      this.getContestRankTable();

    },
    // 获取指定天数之后
    getNextDay(day){
      if(day=='week'){ //获取一周指点
        return  this.getNextDay(-7);
      }else if(day=='month'){ //获取一个月之前
        return this.getNextDay(-30);
      }else if(day=='year'){  //获取一年之前
        return this.getNextDay(-365);
      }else if(day == 'all'){
        return '';
      }else{
        var l = new Date().getTime()+day*24*60*60*1000;
        // 格式化输出 yyyy-MM-dd
        return this.getFomatterDate(new Date(l));
      }
    },
    // 获取公告信息
    getAnnouncementData(){
      announcementApi.getAnnouncementList(this.announcementParams).then(async res=>{
        if(res.data.data) {
          var tables = res.data.data.dataList;

          //获取用户名字
          for (var i = 0; i < tables.length; i++) {
            // console.info(tables[i].userId)
            if (!this.userNames[tables[i].userId]) {
              await userApi.getEasyUserById({"id": tables[i].userId}).then(res2 => {
                if (res2.data.data && res2.data.data.username) {
                  // console.info("success="+res2.data.data.id);
                  this.userNames[res2.data.data.id] = res2.data.data.username;
                } else {
                  this.userNames[tables[i].userId] = '<span style="color:grey">'+this.$t("UnKnownUser")+'</span>';
                }
              });
            }
          }

          this.announcementList = tables;
          this.announcementTotal = res.data.data.total;
          console.info(this.announcementTotal)
          if(this.announcementLoading)this.$message({type:"success",message:this.$t("homeMode.flushSuccess")})
        }
        this.announcementLoading = false;
      },error=>{
        this.announcementLoading = false;
      })
    },

  },
  created() {
    this.getContestTable();
    this.getContestRankTable();
    this.getProblemRankTable();
    this.getAnnouncementData();
  }


}
</script>
<style scoped>
.home-index .rank{
  float: right;


  /*position: absolute;*/
  /*right: 0px;*/
  /*top:65px;*/
  /*vertical-align: top;*/

}
.home-index .announcement{
  width: 620px;
  background-color: white;
  box-shadow: 0 2px 4px rgba(0, 0, 0, .12), 0 0 6px rgba(0, 0, 0, .04);
  overflow: hidden;
  margin-top: 10px;
}
.text {
  font-size: 14px;
}


.clearfix:before,
.clearfix:after {
  display: table;
  content: "";
}
.clearfix:after {
  clear: both
}

.box-card {
  text-align: left;
  width: 440px;
  display: inline-block;
  vertical-align: top;
  margin-right: 30px;
}
.home-index .today .is-selected{
  color: #1989FA;

}
.home-index .today {
   width: 620px;
   font-size: 80%;
 }

.home-index .announcement .announcemet-body{
  width: 520px;
  margin: auto;
  border: 1px solid hsla(0,0%,73.3%,.5);
  border-left: 2px solid #409eff;
  padding: 30px;
  text-align: center;
  margin-bottom: 10px;
}

</style>
<!-- Add "scoped" attribute to limit CSS to this component only -->
<style >
.home-index .el-card__body{
  padding-top: 0px;
}

.el-calendar-table .el-calendar-day {
  height: 40px;
}
.el-calendar-table .el-calendar-day > p{
  height: 100%;
  margin: 0px;
}
div.el-popover,div.el-popper{
  /*background-color: #fafafa;*/
  /*padding: 9px;*/
}

</style>
